package com.netease.financial.common.util;

import android.text.TextUtils;
import android.webkit.WebView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hzwuyufeng on 12/18/15.
 */
public class WebUtils {

    public static String getUrlByRemoveParams(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        int index = url.indexOf('?');
        if (index > 0) {
            url = url.substring(0, index);
        }
        return url;
    }

    //获取url查询参数
    public static String getURLParameter(String url, String param) {

        if (url.indexOf('?') < 0)
            return "";
        String search = url.substring(url.indexOf('?'));
        String pattern = "[?|&]" + param + "=" + "([^&;]+?)(&|#|;|$)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(search);
        if (m.find()) {
            return m.group(1).replaceAll("/\\+/g", "%20");
        }
        return "";
    }

    public static void loadJavascript(WebView webView, String jsContent) {
        webView.loadUrl("javascript:" + jsContent);
    }

    public static void removeLocalStorageItem(WebView webView, String key) {
        final String jsString = String.format("localStorage.removeItem('%s')", key);
        loadJavascript(webView, jsString);
    }

}
